<template>
  <!--   :scroll-with-animation="true" -->
  <view
    :class="{
      'im-messages-wrapper': true,
      'im-wrapper--theme-blue': theme === 'blue'
    }"
  >
    <scroll-view
      id="im_msg_scroll"
      class="im-messages"
      :scroll-y="true"
      :refresher-enabled="false"
      :refresher-threshold="45"
      :upper-threshold="10"
      :scroll-top="scrollTop"
      :scroll-anchoring="true"
      refresher-background="#f9f9f9"
      @scrolltoupper="handleScrolltoupper"
      @scroll="handleScroll"
    >
      <view id="im_msg_scroll_inner">
        <view
          :class="{
            'im-messages__load': true,
            'im-messages__load--ing': msgLoadStatus === 'ing',
            'im-messages__load--end': msgLoadStatus === 'end'
          }"
        >
          <text class="im-messages__loadend">暂无更多消息</text>
          <view class="im-messages__loading">
            <text class="im-icon-loading imani-spin"></text>
          </view>
        </view>
        <template v-for="item in formatMsgLists">
          <view
            v-if="item.type === 'time'"
            :id="item.time"
            :key="item.mid"
            class="im-message im-message-event"
          >
            <text class="im-message-event__content">{{ item.timeText }}</text>
          </view>
          <view
            v-else
            :id="item.mid"
            :class="{
              'im-message': true,
              'im-message-txt': item.msg.type === 'txt',
              'im-message-img': item.msg.type === 'img',
              'im-message-audio': item.msg.type === 'audio',
              'im-message--status-success': item.status === 'success',
              'im-message--status-going': item.status === 'pending',
              'im-message--status-failed': item.status === 'failed',
              'im-message--reverse': item.style === 'self'
            }"
            :key="item.mid"
          >
            <view class="im-message__avatar">
              <view class="im-avatar" shape="square">
                <image
                  class="im-avatar"
                  :src="
                    item[item.style === 'self' ? 'youravatar' : 'useravatar']
                  "
                />
              </view>
            </view>
            <view class="im-message__inner">
              <!-- 昵称 -->
              <!-- <view class="im-message__title">
                <text>
                  {{ item[item.style === 'self' ? 'yourname' : 'username'] }}
                </text>
              </view> -->
              <view class="im-message__content-flex">
                <view class="im-message__content">
                  <view
                    v-if="getMsgRenderTpl(item)"
                    v-html="getMsgRenderTpl(item)"
                  >
                  </view>
                  <!-- 文本消息 -->
                  <view
                    v-else-if="
                      item.msg.type === 'txt' || item.msg.type == 'emoji'
                    "
                  >
                    <view
                      class="im-template"
                      v-for="(d_item, d_index) in parseEmoji(item.msg.data)"
                      :key="d_index"
                    >
                      <text v-if="d_item.type == 'txt'" class="type-txt">
                        {{ d_item.data }}
                      </text>
                      <image
                        v-if="d_item.type == 'emoji'"
                        class="avatar"
                        :src="d_item.data"
                        style="width: 25px; height: 25px"
                      />
                    </view>
                  </view>
                  <!-- 图片消息 -->
                  <image
                    class="type-img"
                    v-else-if="item.msg.type === 'img'"
                    :src="item.msg.thumbnail || item.msg.data"
                    mode="widthFix"
                    @click="previewImage(item)"
                  />
                  <!-- 语音消息 -->
                  <AudioPlay
                    v-else-if="item.msg.type === 'audio'"
                    :imId="imId"
                    :mid="item.mid"
                    :msg="item.msg"
                    :direction="item.style"
                  ></AudioPlay>
                </view>
                <view class="im-message__content-after"></view>
                <view class="im-message__status">
                  <text class="im-icon-loading imani-spin"></text>
                  <text
                    title="重发消息"
                    class="im-icon-prompt"
                    style="color: rgb(255, 37, 37); cursor: pointer"
                  ></text>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>
    <view v-if="loading" class="im-loading">
      <!-- <text class="im-icon-loading imani-spin"></text> -->
    </view>
  </view>
</template>

<script>
import AudioPlay from '../media/audio/audio';

export default {
  name: 'MsgList',

  components: {
    AudioPlay
  },

  data() {
    return {
      // 分页
      msgPage: {
        limit: 20,
        index: 1
      },
      // 状态
      msgLoadStatus: '',

      // 数据
      msgList: [],

      // 滚动条顶部距离
      scrollTop: 0,
      old: {
        scrollTop: 0
      },

      // 是否在加载ing
      upperLoading: false,

      newHeight: 0,

      loading: false,

      sessionKey: ''
    };
  },

  props: {
    theme: {
      type: String,
      default: ''
    },
    // 连接标识
    imId: {
      type: String,
      default: '',
      required: true
    },
    // 接收者
    toUser: {
      type: String,
      default: '',
      required: true
    },
    // 表情
    emoji: {
      type: Object,
      default: () => ({}),
      required: true
    },
    // 表情
    emojiObj: {
      type: Object,
      default: () => ({}),
      required: true
    },
    // 消息渲染函数
    msgRender: {
      type: Function,
      default: function () {}
    }
  },

  computed: {
    formatMsgLists() {
      const lists = [];
      const len = this.msgList.length;

      this.msgList.forEach((msg, msgIndex) => {
        lists.push(msg);
        if (msgIndex + 1 < len) {
          const nextMsg = this.msgList[msgIndex + 1];
          const result =
            Math.floor((nextMsg.time - msg.time) / (30 * 1000)) > 0;

          if (result) {
            lists.push({
              type: 'time',
              time: nextMsg.time,
              mid: `time_${nextMsg.mid}`,
              timeText: this.$hxim.get(this.imId).formatTime(nextMsg.time)
            });
          }
        }
      });
      return lists;
    }
  },

  mounted() {
    this.sessionKey = this.$hxim.get(this.imId).getSessionKey(this.toUser);
    // 更新该用户全部已读
    this.$hxim.get(this.imId).updateUserReadMsg(this.sessionKey);

    // 初始数据
    this.msgLoadStatus = 'ing';
    this.$hxim
      .get(this.imId)
      .getMsgListByCondition({
        sessionKey: this.sessionKey,
        limit: 10
      })
      .then(res => {
        if (res.data.length > 0) {
          this.msgList = res.data.concat(this.msgList);
          this.msgPage.index = res.endIndex;
          this.msgLoadStatus = '';
        } else {
          this.msgLoadStatus = 'end';
        }
        this.scrollToBottom(() => {
          this.$emit('onMsgDataInit');
        });
      });

    // 收到消息
    this.newChatMsgFn = ({ renderableMsg, sessionKey }) => {
      if (this.sessionKey === sessionKey) {
        // 增量处理
        this.msgList.push(renderableMsg);
        this.msgPage.index = Object.assign({}, this.msgPage, {
          index: this.msgPage.index + 1
        });
        this.$hxim
          .get(this.imId)
          .updateUserReadMsg(sessionKey, renderableMsg.mid);
        this.scrollToBottom();
      }
    };
    this.$hxim.get(this.imId).$on('newChatMsg', this.newChatMsgFn);

    // 更新消息
    this.updateChatMsgFn = ({ renderableMsg, sessionKey }) => {
      if (this.sessionKey === sessionKey) {
        // 增量处理
        this.msgList.forEach(m => {
          if (m.mid === renderableMsg.mid) {
            Object.assign(m, renderableMsg);
          }
        });
      }
    };
    this.$hxim.get(this.imId).$on('updateChatMsg', this.updateChatMsgFn);
  },

  destroyed() {
    this.$hxim.get(this.imId).$off('newChatMsg', this.newChatMsgFn);
    this.$hxim.get(this.imId).$off('updateChatMsg', this.updateChatMsgFn);
  },

  methods: {
    // 获取消息模板信息
    getMsgRenderTpl(msg) {
      const msgRender = this.msgRender ? this.msgRender : () => {};
      const tpl = msgRender(msg);
      return tpl;
    },

    scrollToBottom(cb) {
      setTimeout(() => {
        this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this);
          query
            .select('#im_msg_scroll_inner')
            .boundingClientRect(data => {
              this.scrollTop = this.old.scrollTop;
              this.$nextTick(() => {
                this.scrollTop = data.height;
                this.old.scrollTop = this.scrollTop;
                cb && cb();
              });
            })
            .exec();
        });
      }, 300);
    },

    handleScroll(e) {
      this.old.scrollTop = e.detail.scrollTop;
    },

    // 滚动到顶部 (加载历史消息)
    handleScrolltoupper() {
      if (this.upperLoading) {
        return;
      }
      this.msgLoadStatus = 'ing';
      this.upperLoading = true;
      this.$hxim
        .get(this.imId)
        .getMsgListByCondition({
          sessionKey: this.sessionKey,
          startTime: this.msgList[0].time,
          limit: 10
        })
        .then(res => {
          if (res.data.length > 0) {
            this.loading = true;
            this.msgList = res.data.concat(this.msgList);
            this.msgPage.index = res.endIndex;
            this.msgLoadStatus = '';
            const query1 = uni.createSelectorQuery().in(this);
            query1
              .select('#im_msg_scroll_inner')
              .boundingClientRect(data1 => {
                this.$nextTick(() => {
                  const query = uni.createSelectorQuery().in(this);
                  query
                    .select('#im_msg_scroll_inner')
                    .boundingClientRect(data => {
                      this.scrollTop = this.old.scrollTop;

                      this.$nextTick(() => {
                        this.scrollTop = data.height - data1.height;
                        this.old.scrollTop = this.scrollTop;
                        this.upperLoading = false;

                        this.$nextTick(() => {
                          this.loading = false;
                        });
                      });
                    })
                    .exec();
                });
              })
              .exec();
          } else {
            this.msgLoadStatus = 'end';
          }
        });
    },

    // 预览图片
    previewImage(item) {
      const url = item.msg.data;
      uni.previewImage({
        urls: [url]
      });
    },

    /**
     * 解析表情包
     * @method parseEmoji
     * @param {Object} msg 消息文字
     * @return {Object} 消息主体
     */
    parseEmoji(msg) {
      if (
        typeof this.emoji === 'undefined' ||
        typeof this.emoji.map === 'undefined'
      ) {
        return msg;
      }

      const emoji = this.emoji;
      const msgList = [];
      const objList = [];

      for (const face in emoji.map) {
        // eslint-disable-next-line
        if (emoji.map.hasOwnProperty(face)) {
          while (msg.indexOf(face) > -1) {
            msg = msg.replace(face, `^${emoji.map[face]}^`);
          }
        }
      }

      const ary = msg.split('^');
      // const reg = /^e.*g$/;
      const reg = /^data:image/;

      for (let i = 0; i < ary.length; i++) {
        if (ary[i] !== '') {
          msgList.push(ary[i]);
        }
      }

      for (let i = 0; i < msgList.length; i++) {
        if (reg.test(msgList[i])) {
          const obj = {};
          obj.data = msgList[i];
          obj.type = 'emoji';
          objList.push(obj);
        } else {
          const obj = {};
          obj.data = msgList[i];
          obj.type = 'txt';
          objList.push(obj);
        }
      }

      return objList;
    }
  }
};
</script>

<style lang="scss" scoped>
@import '../common/index';
.im-messages-wrapper {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.im-avatar {
  width: 72rpx;
  height: 72rpx;
  line-height: 72rpx;
  font-size: 36rpx;
  font-variant: tabular-nums;
  line-height: 1.5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  list-style: none;
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: hsla(0, 0%, 100%, 0.7);
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  border-radius: 8rpx;
}

.im-avatar--circle {
  border-radius: 50%;
}

.im-avatar img {
  width: 100%;
  height: 100%;
  display: block;
}

.im-messages {
  box-sizing: border-box;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 20rpx 30rpx;
  overflow-anchor: auto;
}

.im-messages::-webkit-scrollbar {
  width: 10rpx;
  height: 10rpx;
}

.im-messages::-webkit-scrollbar-track-piece {
  background-color: transparent;
}

.im-messages::-webkit-scrollbar-thumb:vertical {
  height: 10rpx;
  background-color: #aaa;
}

.im-messages::-webkit-scrollbar-thumb:horizontal {
  width: 10rpx;
  background-color: transparent;
}

.im-messages__load,
.im-messages__time {
  text-align: center;
  font-size: 24rpx;
}

.im-messages__load {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  color: #999;
  line-height: 60rpx;
}

.im-messages__load .im-messages__loadend,
.im-messages__load .im-messages__loading {
  display: none;
}

.im-messages__load--ing .im-icon-loading {
  font-size: 44rpx;
}

.im-messages__load--end .im-messages__loadend,
.im-messages__load--ing .im-messages__loading {
  display: block;
}

.im-message {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  padding: 20rpx 0;
}

.im-message__time {
  color: #b9b9b9;
  padding: 0 10rpx;
}

.im-message__inner {
  position: relative;
  // overflow: hidden;
}

.im-message__avatar {
  padding-right: 20rpx;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.im-message__avatar .im-avatar {
  cursor: pointer;
}

.im-message__title {
  font-size: 24rpx;
  line-height: 32rpx;
  height: 32rpx;
  padding-bottom: 8rpx;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  color: #666;
}

.im-message__content-flex,
.im-message__title {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

.im-message__content {
  font-size: 28rpx;
  line-height: 40rpx;
  padding: 16rpx 20rpx;
  background: #fff;
  border-radius: 8rpx;
  position: relative;
  margin: 0;
  overflow: hidden;
  word-wrap: break-word;
}

.im-message__content .type-img,
.im-message__content video {
  width: 200rpx !important;
  height: 0;
}

.im-message__content:before {
  content: ' ';
  position: absolute;
  top: 12rpx;
  width: 0;
  height: 0;
  border: 8rpx solid transparent;
  left: -8rpx;
  border-left: none;
  border-right-color: #fff;
}

.im-message__content-after {
  display: block;
  width: 96rpx;
  // height: 72rpx;
  padding-left: 12px;
  -webkit-box-flex: 0;
  -ms-flex: none;
  flex: none;
  font-size: 24rpx;
  color: #aaa;
  overflow: hidden;
  visibility: hidden;
}

.im-message__status {
  position: absolute;
  top: 12rpx;
  right: 40rpx;
  color: #aaa;
  font-size: 40rpx;
}

.im-message__status .im-icon-loading,
.im-message__status .im-icon-prompt {
  display: none;
}

.im-message--status-failed .im-icon-prompt,
.im-message--status-going .im-icon-loading {
  display: inline-block;
}

.im-message--status-succeed .im-message__content-after {
  visibility: visible;
}

.im-message--reverse,
.im-message--reverse .im-message__content-flex {
  -webkit-box-orient: horizontal;
  -webkit-box-direction: reverse;
  -ms-flex-direction: row-reverse;
  flex-direction: row-reverse;
}

.im-message--reverse .im-message__content-after {
  padding-right: 12rpx;
  padding-left: 0;
  text-align: right;
}

.im-message--reverse .im-message__title {
  -webkit-box-orient: horizontal;
  -webkit-box-direction: reverse;
  -ms-flex-direction: row-reverse;
  flex-direction: row-reverse;
}

.im-message--reverse .im-message__status {
  left: 52rpx;
  right: auto;
}

.im-message--reverse .im-message__content {
  background: #35d863;
}

.im-message--reverse .im-message__content:before {
  content: ' ';
  position: absolute;
  top: 12rpx;
  width: 0;
  height: 0;
  border: 8rpx solid transparent;
  left: auto;
  right: -8rpx;
  border-right: none;
  border-left-color: #35d863;
}

.im-message--reverse .im-message__title {
  text-align: right;
}

.im-message--reverse .im-message__avatar {
  padding-right: 0;
  padding-left: 20rpx;
}

.im-message--hide-title .im-message__avatar {
  padding-top: 20rpx;
}

.im-message--hide-title .im-message__status {
  top: 28rpx;
}

.im-message--hide-title .im-message__content {
  position: relative;
  top: -20rpx;
}

.im-message--hide-title .im-message__content:before {
  top: 28rpx;
}

.im-message-txt .im-message__content img {
  width: 36rpx;
  height: 36rpx;
  display: inline-block;
  background: transparent;
  position: relative;
  top: -2rpx;
  padding: 0 4rpx;
  vertical-align: middle;
}

.im-message-img .im-message__content {
  padding: 0;
  cursor: pointer;
  overflow: hidden;
}

.im-message-img .im-message__content .type-img {
  max-width: 100%;
  min-width: 100px;
  display: block !important;
  // height: 240rpx !important;
}

.im-message-file .im-message__content {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  cursor: pointer;
  width: 400rpx;
  background: #fff;
  padding: 24rpx 36rpx;
  overflow: hidden;
}

.im-message-file .im-message__content p {
  margin: 0;
}

.im-message-file__tip {
  display: none;
}

.im-message-file__inner {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}

.im-message-file__name {
  font-size: 28rpx;
}

.im-message-file__byte {
  font-size: 24rpx;
  color: #aaa;
}

.im-message-file__sfx {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  font-weight: 700;
  font-size: 68rpx;
  color: #ccc;
}

.im-message-event__content,
.im-message-file__sfx {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.im-message-event__content {
  display: inline-block;
  background: #e9e9e9;
  color: #aaa;
  font-size: 24rpx;
  margin: 0 auto;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}

.im-wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  font-size: 28rpx;
  font-family: Microsoft YaHei;
  background: #efefef;
  -webkit-transition: all 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: all 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);
  position: relative;
}

.im-wrapper p {
  margin: 0;
}

.im-wrapper img {
  vertical-align: middle;
  border-style: none;
}

.im-template {
  display: inline;
  line-height: 0;
  vertical-align: middle;
}

.im-messages {
  flex: 1;
  // height: auto;
}

.im-wrapper--theme-blue .im-message__content {
  background: #f3f3f3;
}

.im-wrapper--theme-blue .im-message__content:before {
  border-right-color: #f3f3f3;
}

.im-wrapper--theme-blue .im-message--reverse .im-message__content {
  background: #e6eeff;
}

.im-wrapper--theme-blue .im-message--reverse .im-message__content:before {
  border-left-color: #e6eeff;
}
</style>
